import json
from django.core.paginator import Paginator
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from .models import Article, MiniUser
import os
from django.conf import settings

# Create your views here.


def get_banner(request):
    """
    返回小程序文章列表接口
    :param request:
    :return:
    """
    artical_list = Article.objects.all()
    result = [{'postId': item.id, 'avatar': item.avatar, 'date': item.date,
               'title': item.title,
               'imgSrc': item.imgSrc,
               'content': item.content,
               'collection': item.collection,
               'reading': item.reading
               } for item in artical_list]
    return JsonResponse({'status': 1, 'msg': '返回成功', 'data': result})


# @csrf_exempt
def login_check(request):
    """
    验证账号密码的正确性，接口返回
    :param request:
    :return:
    """
    if request.method == 'POST':
        username = request.POST['phone']
        password = request.POST['password']
        # 目前我们还没有设计用户表，所以验证的数据都还是自己定义的
        # is_exist = MiniUser.objects.filter(phoneNumber=username).values('password')
        # print(is_exist)
        # if is_exist:
        #     is_exist = list(is_exist)
        #     if password == is_exist[0]['password']:
        #         return JsonResponse({'code': 1, 'msg': '登录成功', 'data': {}})
        #     else:
        #         return JsonResponse({'code': -1, 'msg': '密码错误', 'data': {}})
        # else:
        #     return JsonResponse({'code': -1, 'msg': '用户不存在', 'data': {}})

        try:
            is_exist = MiniUser.objects.filter(phoneNumber=username).get()
            if is_exist:
                if password == is_exist.password:
                    print(is_exist.birthday)
                    # 写入session
                    request.session['user_info'] = json.dumps({
                        'username': is_exist.userName,
                        'id': is_exist.id,
                        'address': is_exist.address,
                        'birthday': str(is_exist.birthday)
                    })
                    return JsonResponse({'code': 1, 'msg': '登录成功', 'data': {}})
                else:
                    return JsonResponse({'code': -1, 'msg': '密码错误', 'data': {}})
        except Exception as e:
            print(e)
            return JsonResponse({'code': -1, 'msg': '用户不存在', 'data': {}})

    else:
        return JsonResponse({'code': -1, 'msg': '请求方法错误', 'data': {}})


def user_list(request):
    """
    模拟数据，返回给前端的数据table表格
    :param request:
    :return:
    """
    current_page = request.GET['page']
    limit = request.GET['limit']

    # 讲字典的时候，取一个不存在建名
    if request.GET.get('key_words', None):
        keyword = request.GET['key_words']
        users = MiniUser.objects.filter(status=1).filter(userName__icontains=keyword).all().order_by('-id').values()
    else:
        users = MiniUser.objects.filter(status=1).all().order_by('-id').values()

    results = [
        {
            'id': x['id'],
            'userName': x['userName'],
            'nickName': x['nickName'],
            'birthday': x['birthday'],
            'email': x['email'],
            'register_time': x['register_time']
         } for x in users
   ]

    p = Paginator(results, limit)  # limit 传递10
    counter = p.count
    res = p.page(current_page)  # page  传递 1
    # print(res)
    res = res.object_list
    # print(res)
    return JsonResponse({'code': 0, 'msg': '返回成功', 'count': counter, 'data': res})


def del_user(request):
    """
    删除数据
    :param request:
    :return:
    """
    id = request.POST['id']
    # print(res)
    # 从session里取出用户信息（id字段），跟post过来的id去比较
    # 如果相同呢？
    # del request.session['user_info']
    user_info = request.session.get('user_info')
    user_info = json.loads(user_info)
    user_id = user_info['id']

    if user_id == int(id):
        return JsonResponse({'code': 1, 'msg': '不能删除自己', 'data': []})

    res = MiniUser.objects.filter(pk=id).update(status=0)
    if res:
        return JsonResponse({'code': 0, 'msg': '删除成功', 'data': []})
    else:
        return JsonResponse({'code': 1, 'msg': '删除失败', 'data': []})


def user_add(request):
    """
    新增用户数据
    :param request:
    :return:
    """
    try:
        userObj = MiniUser()
        userObj.userName = request.POST['userName']
        userObj.nickName = request.POST['nickName']
        userObj.password = request.POST['password']
        userObj.email = request.POST['email']
        userObj.phoneNumber = request.POST['phoneNumber']
        userObj.birthday = request.POST['birthday']
        userObj.sex = request.POST['sex']
        userObj.address = request.POST['address']
        userObj.status = 1
        userObj.save()
        return JsonResponse({'code': 0, 'msg': '添加成功', 'data': []})
    except Exception as e:
        return JsonResponse({'code': 1, 'msg': '添加失败', 'data': []})


def user_edit(request):
    user_id = request.POST['user_id']
    try:
        ret = MiniUser.objects.filter(id=user_id).update(
            userName=request.POST['userName'],
            nickName=request.POST['nickName'],
            password=request.POST['password'],
            email=request.POST['email'],
            phoneNumber=request.POST['phoneNumber'],
            birthday=request.POST['birthday'],
            sex=request.POST['sex'],
            address=request.POST['address']
        )
        print(ret)
        if ret:
            return JsonResponse({'code': 0, 'msg': '修改成功', 'data': []})
        else:
            return JsonResponse({'code': 1, 'msg': '修改失败', 'data': []})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 1, 'msg': '修改失败', 'data': []})


def article_list(request):
    """
    模拟数据，返回给前端的数据table表格
    :param request:
    :return:
    """
    current_page = request.GET['page']
    limit = request.GET['limit']

    # 讲字典的时候，取一个不存在建名
    if request.GET.get('key_words', None):
        keyword = request.GET['key_words']
        articles = Article.objects.filter(title__icontains=keyword).all().order_by('-id').values()
    else:
        articles = Article.objects.all().order_by('-id').values()

    results = [
        {
            'id': x['id'],
            'title': x['title'],
            'imgSrc': x['imgSrc'],
            'reading': x['reading'],
            'collection': x['collection'],
            'dateTime': x['dateTime'],
            'author': x['author']
         } for x in articles
   ]

    p = Paginator(results, limit)  # limit 传递10
    counter = p.count
    res = p.page(current_page)  # page  传递 1
    # print(res)
    res = res.object_list
    # print(res)
    return JsonResponse({'code': 0, 'msg': '返回成功', 'count': counter, 'data': res})


def del_article(request):
    """
    删除数据
    :param request:
    :return:
    """
    id = request.POST['id']

    res = Article.objects.filter(pk=id).delete()
    if res:
        return JsonResponse({'code': 0, 'msg': '删除成功', 'data': []})
    else:
        return JsonResponse({'code': 1, 'msg': '删除失败', 'data': []})


def article_add(request):
    """
    新增用户数据
    :param request:
    :return:
    """
    try:
        artObj = Article()
        artObj.title = request.POST['title']
        artObj.author = request.POST['author']
        artObj.imgSrc = request.POST['imgSrc']
        artObj.collection = request.POST['collection']
        artObj.reading = request.POST['reading']
        artObj.dateTime = request.POST['dateTime']
        artObj.content = request.POST['content']

        artObj.avatar = ''
        artObj.headImgSrc = ''
        artObj.detail = ''
        artObj.music = ''
        artObj.date = ''
        artObj.save()
        return JsonResponse({'code': 0, 'msg': '添加成功', 'data': []})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 1, 'msg': '添加失败', 'data': []})


def upload(request):
    file = request.FILES['file']
    print("上传的文件名是：", file.name)
    filename = os.path.join(settings.MEDIA_ROOT, file.name)
    with open(filename, "wb") as f:
        data = file.file.read()
        f.write(data)

    # -*- coding: utf-8 -*-
    # flake8: noqa
    from qiniu import Auth, put_file, etag
    import qiniu.config
    # 需要填写你的 Access Key 和 Secret Key
    access_key = 'vWggyODEqOPueOBxjq0wmpiXDGdZ4fZIlKRaLyyz'
    secret_key = '_fCsA6zGS6dRkk3aa8CaYhSrP4vTxF6HTn2PZGEd'
    # 构建鉴权对象
    q = Auth(access_key, secret_key)
    # 要上传的空间
    bucket_name = '22dashuju'
    # 上传后保存的文件名
    key = file.name
    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    # 要上传文件的本地路径
    localfile = filename
    ret, info = put_file(token, key, localfile, version='v2')
    print(info)
    assert ret['key'] == key
    assert ret['hash'] == etag(localfile)

    res_path = 'http://s61o3wi19.hn-bkt.clouddn.com/' + file.name

    return JsonResponse({'code': 0, 'msg': '上传成功', 'data': {'filepath': res_path}})


def article_edit(request):
    article_id = request.POST['id']
    try:
        ret = Article.objects.filter(id=article_id).update(
            title=request.POST['title'],
            imgSrc=request.POST['imgSrc'],
            reading=request.POST['reading'],
            collection=request.POST['collection'],
            author=request.POST['author'],
            dateTime=request.POST['dateTime'],
            content=request.POST['content']
        )
        print(ret)
        if ret:
            return JsonResponse({'code': 0, 'msg': '修改成功', 'data': []})
        else:
            return JsonResponse({'code': 1, 'msg': '修改失败', 'data': []})
    except Exception as e:
        print(e)
        return JsonResponse({'code': 1, 'msg': '修改失败', 'data': []})


def logout(request):
    # 删除session
    del request.session['user_info']
    return JsonResponse({'code': 0, 'msg': '退成成功', 'data': {'url': 'http://127.0.0.1:8080/test_admin/login'}})
